package tgc.edu.exam.web.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ShortBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import tgc.edu.exam.custom.AjaxResult;
import tgc.edu.exam.custom.CommonController;
import tgc.edu.exam.custom.DataGridParam;
import tgc.edu.exam.custom.DataGridUtils;
import tgc.edu.exam.custom.ImportExcel;
import tgc.edu.exam.custom.TablePageable;
import tgc.edu.exam.custom.dict.entity.SystemData;
import tgc.edu.exam.custom.dict.entity.SystemDictionaries;
import tgc.edu.exam.custom.dict.service.SystemDataService;
import tgc.edu.exam.custom.dict.service.SystemDicationariesService;
import tgc.edu.exam.entity.AskForleave;
import tgc.edu.exam.entity.CurriculumPlan;
import tgc.edu.exam.entity.Student;
import tgc.edu.exam.entity.SysFile;
import tgc.edu.exam.entity.SysRole;
import tgc.edu.exam.entity.SysUser;
import tgc.edu.exam.entity.TbClass;
import tgc.edu.exam.entity.Teacher;
import tgc.edu.exam.security.UserUtils;
import tgc.edu.exam.service.StudentService;
import tgc.edu.exam.service.SysFileService;
import tgc.edu.exam.service.SysRoleService;
import tgc.edu.exam.service.TbClassService;
import tgc.edu.exam.web.form.StudentForm;

@Controller
@RequestMapping(value = "/student")
public class StuController extends CommonController<Student, UUID, StudentForm> {
	@Autowired
	private TbClassService csService;
	@Autowired
	private StudentService service;
	@Autowired
	private SysRoleService roleService;
	@Autowired
	private SystemDicationariesService dictService;
	@Autowired
	private SystemDataService dataService;
	@Autowired
	private UserUtils userUtils;
	@Autowired
	private SysFileService fileservice;
	@Autowired
	private TbClassService tbClassService;

	@RequestMapping(value = "/audit")
	public void audit(ModelMap map) {
		SysUser sysUser = userUtils.getUser();
		if (sysUser != null) {
			Specification<TbClass> spec = buildSpec3(sysUser);
			List<TbClass> bjs = csService.findAll(spec);
			map.put("bjs", bjs);
		} else {
			Specification<TbClass> spec = buildSpec3(null);
			List<TbClass> bjs = csService.findAll(spec);
			map.put("bjs", bjs);
		}
	}
	
	@RequestMapping(value="/lead")
	public void lead() {
		
	}
	
	/**
	 * 导入学员信息
	 * @param id
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/updateLead")
	@ResponseBody
	public Object updateLead(@RequestParam( value="files",required=false)MultipartFile file, String tbClassId) {
		//实例化工具类
		ImportExcel excelReader = new ImportExcel();
		InputStream is;
		try {
			is = file.getInputStream();
		} catch (IOException e) {
			return "导入失败";
		}
		//导入excel
		excelReader.readExcelContent(is);
		Map<Integer, String> map = excelReader.readExcelContent(is);
		//is.close();
		
		int a = 0, b = 0;
		for(int i = 3; i <= map.size()+1; i++) {
			System.out.println(map.get(i).toString()+"====");
			System.out.println(tbClassService.findById(UUID.fromString(tbClassId))+"++++++++++");
			try {
				String[] split = map.get(i).split("-");
				System.out.println(split[10]+"------");
				Student stu = new Student();
				stu.setIsUsed(true);
				stu.setType("已同意");
				stu.setTbClass(tbClassService.findById(UUID.fromString(tbClassId)));
				stu.setUsername(split[0]);
				stu.setIdcode(split[0]);
				BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
				stu.setPassword(encoder.encode(split[0].substring(split[0].length()-6, split[0].length())));
				stu.setName(split[1]);
				stu.setSex(split[2]);
				stu.setNation(split[3]);
				stu.setPolitics(split[4]);
				stu.setDegree(split[5]);
				stu.setEmail(split[6]);
				stu.setOfficetel(split[7]);
				stu.setJob(split[8]);
				stu.setAddress(split[9]);
				stu.setPhone(split[10]);
				stu.setWorkUnit(split[11]);
				SysRole role = roleService.findbyCode("ROLE_STUDENT");
				stu.getRoles().add(role);
				service.save(stu);
				/*
				String password = pwd.substring(pwd.length()-6, pwd.length());
				form.setPassword(encoder.encode(password));*/
				a++;
			} catch (Exception e) {
				b++;
			}
		}
		if(b == 0) {
			return "导入成功！";
		}else {
			return "导入成功数据："+a+"，失败数据："+b;			
		}
	}
	
	@RequestMapping(value="/derive")
	@ResponseBody
	public void derive(String id, HttpServletRequest request, HttpServletResponse response) {
		if(id != null && !id.equals("")) {
			List<Student> stu = service.findByTbClassIdAndIsUsed(UUID.fromString(id), true);
			TbClass tbClass = csService.findById(UUID.fromString(id));
			String startTime = tbClass.getStartTime();
			String[] split = startTime.split("-");
			String closeTime = tbClass.getCloseTime();
			String[] split2 = closeTime.split("-");
			String subject = tbClass.getSubject();
			try {
				HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象
				HSSFSheet sheet = workbook.createSheet("学员结业信息");
				String[] fieldnames = {"姓名", "开始日期", "结业日期", "班级主题", "证字第"};
				HSSFRow row = sheet.createRow(0);
				for(int i = 0; i < fieldnames.length; i++) {
					HSSFCell cell = row.createCell(i);
					cell.setCellValue(fieldnames[i]);
				}
				
				for(int i = 0; i < stu.size(); i++) {
					Student s = stu.get(i);
					String name = s.getName();
					String zzd = s.getSerial();
					String ksrq = split[0]+" 年 "+split[1]+" 月 "+split[2]+" 日";
					String jsrq = split2[0]+" 年 "+split2[1]+" 月 "+split2[2]+" 日";
					String bjzt = subject;
					row = sheet.createRow(i+1);
					HSSFCell cell = row.createCell(0);
					cell.setCellValue(name);
					cell = row.createCell(1);
					cell.setCellValue(ksrq);
					cell = row.createCell(2);
					cell.setCellValue(jsrq);
					cell = row.createCell(3);
					cell.setCellValue(bjzt);
					cell = row.createCell(4);
					cell.setCellValue(zzd);
				}
				
				/*HSSFCellStyle cellStyle=workbook.createCellStyle();
				HSSFCellStyle cellStyle1=workbook.createCellStyle();
				HSSFFont font = workbook.createFont();
				HSSFFont font1 = workbook.createFont();
				font.setFontHeightInPoints((short) 20);
				font1.setFontHeightInPoints((short) 14);
				font.setFontName("仿宋");
				font1.setFontName("仿宋");
				cellStyle.setWrapText(true);   
				cellStyle.setFont(font);
				cellStyle1.setFont(font1);
		        HSSFCellStyle style = workbook.createCellStyle();
		        style.setBorderBottom(BorderStyle.THIN);
		        style.setBorderLeft(BorderStyle.THIN);//左边框
		        style.setBorderRight(BorderStyle.THIN);//右边框
		        style.setBorderTop(BorderStyle.THIN); //上边框*/		        

				/*for (Student s : stu) {
					String str1 = "     "+s.getName()+"    同志于 "+split[0]+" 年 "+split[1]+" 月 "+split[2]+" 日至 "+split2[0]+" 年 "+split2[1]+" 月 "+split2[2]+" 日在县委党校中青年干部 “ "+subject+" ” 培训班学习，经考试考核合格，准予结业，特发此证。";
					String str2 = "   证字第："+s.getSerial();
					String str3 = "中共秭归县委党校  ";
					String str4 = split2[0]+" 年 "+split2[1]+" 月 "+split2[2]+" 日";
					
					HSSFSheet sheet = workbook.createSheet(s.getName()); // 创建工作表
					HSSFRow row = sheet.createRow(13);// 创建所需的行
					HSSFCell teacher = row.createCell(6);
					HSSFRow rowt2 = sheet.createRow(31);
					HSSFCell teacher2 = rowt2.createCell(2);
					HSSFRow rowt3 = sheet.createRow(29);
					HSSFCell teacher3 = rowt3.createCell(9);
					HSSFCell teacher4 = rowt2.createCell(9);
					HSSFRow row2 = sheet.createRow(16);
					HSSFCell teacher5 = row2.createCell(3);
					HSSFRow rowt4 = sheet.createRow(17);
					HSSFRow rowt5 = sheet.createRow(18);
					HSSFRow rowt6 = sheet.createRow(19);
					HSSFRow rowt7 = sheet.createRow(20);
					HSSFRow rowt8 = sheet.createRow(21);
					HSSFCell teacher6 = rowt4.createCell(3);
					HSSFCell teacher7 = rowt5.createCell(3);
					HSSFCell teacher8 = rowt6.createCell(3);
					HSSFCell teacher9 = rowt7.createCell(3);
					HSSFCell teacher10 = rowt8.createCell(3);
					teacher5.setCellStyle(style);
					teacher6.setCellStyle(style);
					teacher7.setCellStyle(style);
					teacher8.setCellStyle(style);
					teacher9.setCellStyle(style);
					teacher10.setCellStyle(style);
					
					sheet.addMergedRegion(new CellRangeAddress(13, 23, 6, 11));
					sheet.addMergedRegion(new CellRangeAddress(16, 21, 3, 3));
					sheet.addMergedRegion(new CellRangeAddress(31, 32, 2, 4));
					sheet.addMergedRegion(new CellRangeAddress(29, 30, 9, 11));
					sheet.addMergedRegion(new CellRangeAddress(31, 32, 9, 11));
					
					teacher.setCellValue(str1);
					teacher.setCellStyle(cellStyle);
					teacher2.setCellValue(str2);
					teacher2.setCellStyle(cellStyle1);
					teacher3.setCellValue(str3);
					teacher3.setCellStyle(cellStyle1);
					teacher4.setCellValue(str4);
					teacher4.setCellStyle(cellStyle1);
				}*/
				if (workbook != null) {
					try {
						String agent = request.getHeader("USER-AGENT");
						String fileName = tbClass.getName()+".xls";
						if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
							fileName = "=?UTF-8?B?" + Base64Utils.encodeToString(fileName.getBytes("UTF-8")) + "?=";
						}
						String headStr = "attachment; filename=\"" + fileName + "\"";
						response.setContentType("APPLICATION/OCTET-STREAM");
						response.setHeader("Content-Disposition", headStr);
						OutputStream out1 = response.getOutputStream();
						workbook.write(out1);
						workbook.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	@RequestMapping(value="/performanceSave")
	@ResponseBody
	public Object performanceSave(String id, Double points, Double performance) {
		Student stu = service.findById(UUID.fromString(id));
		if(points != null) {
			stu.setPoints(points);
		}else {
			stu.setPoints((double) 100);
		}
		if(performance != null) {
			stu.setPerformance(performance);
		}
		service.save(stu);
		return "ok";
	}
	
	@RequestMapping(value="/performance")
	public void performance(ModelMap map) {
		List<TbClass> bjs = csService.findAll();
		map.put("bjs", bjs);
	}

	@RequestMapping(value = "/instant")
	@ResponseBody
	public Object instant() {
		String msg = "";
		try {
			SysUser user = userUtils.getUser();
			Specification<Student> spec = buildSpec1(user,null);
			List<Student> students = service.findAll(spec);
			SysRole role = roleService.findbyCode("ROLE_STUDENT");
			if (students.size() != 0) {
				for (Student student : students) {
					student.setType("已通过");
					student.setIsUsed(true);
					student.getRoles().add(role);
					service.save(student);
					TbClass tbClass = student.getTbClass();
					if(tbClass.getClassSize()==null) {
						tbClass.setClassSize(1);
					}else {
						tbClass.setClassSize(tbClass.getClassSize()+1);
					}
					tbClassService.save(tbClass);
				}
				msg = "操作完成！";
			} else {
				msg = "没有要审核的数据哟！";
			}
		} catch (Exception e) {
			msg = "数据异常！请联系管理员";
		}
		return msg;
	}
	
	/**
	 * 上传结业证书页面
	 */
	@RequestMapping(value="/certificate")
	public void certificate(String id, ModelMap map) {
		Student stu = new Student();
		if(id != null) {
			stu = service.findById(UUID.fromString(id));
		}
		map.put("model", stu);
	}
	
	/**
	 * 证书上传
	 */
	@RequestMapping(value="/updateCertificate")
	@ResponseBody
	public void updateCertificate(String certificateuuid, String id) {
		Student student = service.findById(UUID.fromString(id));
		student.setCertificateuuid(certificateuuid);
		SysFile file = fileservice.findByUuid(certificateuuid);
		file.setIsUsed(true);
		fileservice.save(file);
		service.save(student);
	}

	@RequestMapping(value = "/agree")
	@ResponseBody
	public Object agree(String id) {
		try {
			Student student = service.findById(UUID.fromString(id));
			if (student != null) {
				SysRole role = roleService.findbyCode("ROLE_STUDENT");
				student.setType("已通过");
				student.setIsUsed(true);
				student.getRoles().add(role);
				service.save(student);
				TbClass tbClass = student.getTbClass();
				if(tbClass.getClassSize()==null) {
					tbClass.setClassSize(1);
				}else {
					tbClass.setClassSize(tbClass.getClassSize()+1);
				}
				tbClassService.save(tbClass);
				return "操作完成！";
			} else {
				return "数据异常！请联系管理员";
			}
		} catch (Exception e) {
			return "数据异常！请联系管理员";
		}
	}

	@RequestMapping(value = "/repulse")
	@ResponseBody
	public Object refuse(String id, String yuanyi) {
		String msg = "数据出错！请联系管理员";
		try {
			Student student = service.findById(UUID.fromString(id));
			if (student != null) {
				student.setType("已拒绝");
				student.setYuanying(yuanyi);
				student.setTbClass(null);
				service.save(student);
				msg = "操作成功！";
			}
		} catch (Exception e) {
			msg = "数据异常！请联系管理员";
		}
		return msg;
	}
	
	/**
	 * 班级显示班级成员
	 * @param param
	 * @param tbClassid
	 * @return
	 */
	@RequestMapping(value="/page2")
	@ResponseBody
	public Object page2(DataGridParam param, String tbClassid) {
		Sort sort=Sort.by("createDate");
		Pageable pageable = param.getPageable(sort);
		Specification<Student> spec = buildSpec2(tbClassid);
		Page<Student> page = service.findAll(spec, pageable);
		return DataGridUtils.buildResult(page);
	}
	
	private Specification<Student> buildSpec2(String tbClassid) {
		Specification<Student> spec = new Specification<Student>() {

			@Override
			public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules = new HashSet<>();
				if(StringUtils.hasText(tbClassid)) {
					rules.add(cb.equal(root.get("tbClass").get("id"), UUID.fromString(tbClassid)));
				}
				rules.add(cb.equal(root.get("isUsed"), true));
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}

	@RequestMapping(value = "/page1")
	@ResponseBody
	public Object page1(TablePageable pageParam , String bjuuid) {
		PageRequest pageable = pageParam.bulidPageRequest();
		SysUser user = userUtils.getUser();
		Specification<Student> spec = buildSpec1(user,bjuuid);
		Page<Student> page = service.findAll(spec, pageable);
		return DataGridUtils.buildResult(page);
	}

	private Specification<Student> buildSpec1(SysUser user, String bjuuid) {
		Specification<Student> spec = new Specification<Student>() {

			@Override
			public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules = new HashSet<>();
				if (user != null) {
					rules.add(cb.equal(root.get("tbClass").get("teacherId").get("id"), user.getId()));
				}
				if(StringUtils.hasText(bjuuid)) {
					rules.add(cb.equal(root.get("tbClass").get("id"), UUID.fromString(bjuuid)));
				}
				rules.add(cb.equal(root.get("type"), "待审核"));
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}

	@Override
	public void edit(StudentForm form, ModelMap map) throws InstantiationException, IllegalAccessException {
		List<TbClass> bjs = csService.findAll();
		map.put("bjs", bjs);
		SystemDictionaries systemDictionaries = dictService.findByCode("nation");
		List<SystemData> data = dataService.findBySystemDictionaries(systemDictionaries);
		map.put("data", data);
		SystemDictionaries systemDictionaries1 = dictService.findByCode("political_outlook");
		List<SystemData> data1 = dataService.findBySystemDictionaries(systemDictionaries1);
		map.put("data1", data1);
		SystemDictionaries systemDictionaries2 = dictService.findByCode("education");
		List<SystemData> data2 = dataService.findBySystemDictionaries(systemDictionaries2);
		map.put("data2", data2);
		SystemDictionaries systemDictionaries3 = dictService.findByCode("Class_duties");
		List<SystemData> data3 = dataService.findBySystemDictionaries(systemDictionaries3);
		map.put("data3", data3);
		super.edit(form, map);
	}

	@Override
	public Object save(StudentForm form) {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			UUID id = form.getId();
			Student model = new Student();
			String name = userUtils.getName();
			if (id == null) {
				String pwd = form.getIdcode();
				BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
				String password = pwd.substring(pwd.length()-6, pwd.length());
				form.setPassword(encoder.encode(password));
				form.setIsUsed(true);
				form.setType("已同意");
				SysRole role = roleService.findbyCode("ROLE_STUDENT");
				model.getRoles().add(role);
				model.setCreateDate(sdf.format(new Date()));
				model.setCreateName(name);
			}else {
				model=service.findById(id);
				model.setUpdateDate(sdf.format(new Date()));
				model.setUpdateName(name);
			}
			form.setUsername(form.getIdcode());
			if(!form.getFileuuid().equals("") && form.getFileuuid() != null) {
				SysFile file = fileservice.findByUuid(form.getFileuuid());
				file.setIsUsed(true);
				fileservice.save(file);
			}
			BeanUtils.copyProperties(form, model,"id");
			service.save(model);
		
			//T model=clazz.newInstance();
			//String name = userUtils.getName();
			//ID id = form.getId();
//			if(id!=null) {
//				model=baseService.findById(id);
//				model.setUpdateDate(sdf.format(new Date()));
//				model.setUpdateName(name);
//			}else {
//				model.setCreateDate(sdf.format(new Date()));
//				model.setCreateName(name);
//			}
//			BeanUtils.copyProperties(form, model,"id");
//			baseService.save(model);
			return new AjaxResult("数据保存成功");
		} catch (Exception e) {
			return new AjaxResult(false,"数据保存失败");
		}
	}

	@RequestMapping(value = "select")
	@ResponseBody
	public Object select(String id) {
		TbClass tbClass = csService.findById(UUID.fromString(id));
		Specification<Student> spec1 = buildSpec4(tbClass);
		List<Student> list = service.findAll(spec1);
		return list;
	}
	
	
	
	private Specification<Student> buildSpec4(TbClass tbClass2) {
		Specification<Student> spec = new Specification<Student>() {

			@Override
			public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules = new HashSet<>();

				rules.add(cb.equal(root.get("tbClass").get("id"), tbClass2.getId()));
				rules.add(cb.equal(root.get("isUsed"), true));

				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}

	@Override
	public void manage(ModelMap map) {
		boolean ishas = false;
		SysUser sysUser = userUtils.getUser();
		if (sysUser != null) {
			List<SysRole> roles = sysUser.getRoles();
			for (SysRole sysRole : roles) {
				List<SysRole> children = sysRole.getChildren();
				for (SysRole sysRole2 : children) {
					String code = "ROLE_CHKWQXY";
					String rolecode = sysRole2.getCode();
					if (code.equals(rolecode)) {
						ishas = true;
					}
				}
			}
			if (ishas) {
				Specification<TbClass> spec = buildSpec3(null);
				List<TbClass> bjs = csService.findAll(spec);
				Specification<Student> spec1 = buildSpec4(bjs.get(0));
				List<Student> list = service.findAll(spec1);
				map.put("bjs", bjs);
				map.put("stu", list);
			} else {
				Specification<TbClass> spec = buildSpec3(sysUser);
				List<TbClass> bjs = csService.findAll(spec);
				if(bjs.size()!=0) {
					Specification<Student> spec1 = buildSpec4(bjs.get(0));
					List<Student> list = service.findAll(spec1);
					map.put("bjs", bjs);
					map.put("stu", list);
				}
			}
		} else {
			ishas = true;
			Specification<TbClass> spec = buildSpec3(null);
			List<TbClass> bjs = csService.findAll(spec);
			List<Student> list = service.findByTbClassId(bjs.get(0).getId());
			map.put("bjs", bjs);
			map.put("stu", list);
		}
		map.put("ishas", ishas);

		super.manage(map);
	}

	private Specification<TbClass> buildSpec3(SysUser sysUser) {
		Specification<TbClass> spec = new Specification<TbClass>() {
			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<TbClass> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules = new HashSet<>();
				if (sysUser != null) {
					rules.add(cb.equal(root.get("teacherId").get("id"), sysUser.getId()));
				}
				rules.add(cb.notEqual(root.get("classStatus").get("state"), "结业"));
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}

	@RequestMapping(value = "/banjiselect")
	@ResponseBody
	public Object banjiselect(boolean isstart) {
		if (isstart) {
			List<TbClass> bjs = csService.findAll();
			List<TbClass> list = new ArrayList<>();
			for (TbClass tbClass : bjs) {
				String state = tbClass.getClassStatus().getState();
				if ("结业".equals(state)) {
					tbClass.setName(tbClass.getName() + "(结业班级)");
					list.add(tbClass);
				}
			}
			return list;
		} else {
			Specification<TbClass> spec = buildSpec3(null);
			List<TbClass> bjs = csService.findAll(spec);
			return bjs;
		}
	}

	@Override
	public Specification<Student> buildSpec(StudentForm form) {
		Specification<Student> spec = new Specification<Student>() {

			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules = new HashSet<>();
				String name = form.getName();
				if (StringUtils.hasText(name)) {
					rules.add(cb.like(root.get("name"), "%" + name + "%"));
				}
				String username = form.getUsername();
				if (StringUtils.hasText(username)) {
					rules.add(cb.like(root.get("username"), "%" + username + "%"));
				}
				String sex = form.getSex();
				if (StringUtils.hasText(sex)) {
					rules.add(cb.equal(root.get("sex"), sex));
				}
				String address = form.getAddress();
				if (StringUtils.hasText(address)) {
					rules.add(cb.like(root.get("address"), "%" + address + "%"));
				}
				String phone = form.getPhone();
				if (StringUtils.hasText(phone)) {
					rules.add(cb.like(root.get("phone"), "%" + phone + "%"));
				}
				String workUnit = form.getWorkUnit();
				if (StringUtils.hasText(workUnit)) {
					rules.add(cb.like(root.get("workUnit"), "%" + workUnit + "%"));
				}
				String bjuuid = form.getBjuuid();
				if (StringUtils.hasText(bjuuid)) {
					rules.add(cb.equal(root.get("tbClass").get("id"), UUID.fromString(bjuuid)));
				}
				String suuid = form.getSuuid();
				if (StringUtils.hasText(suuid)) {
					rules.add(cb.equal(root.get("id"), UUID.fromString(suuid)));
				}
				boolean isUsed = form.getIsUsed();
				rules.add(cb.equal(root.get("isUsed"), isUsed));
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;

	}

}
